import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../common/widgets.dart';

class SettingPage extends StatefulWidget {
  @override
  SettingState createState() => SettingState();
}

class SettingState extends State<SettingPage> {
  final MethodChannel settingMethodChannel = const MethodChannel('example.flutter.settings/method_channel');
  final TextEditingController appIdController = TextEditingController();
  final TextEditingController reportUrlController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('设置'),
      ),
      body: Center(
        child: ListView(
          padding: const EdgeInsets.only(left: 16.0, right: 16.0, top: 8.0, bottom: 8.0),
          children: <Widget>[
            buildButton(
              context,
              '私有化部署，设置后请重启应用',
              () => _privatizationSettingsDialog(context),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    appIdController.dispose();
    reportUrlController.dispose();
    super.dispose();
  }

  Future<void> _privatizationSettingsDialog(BuildContext context) async {
    appIdController.text = await settingMethodChannel.invokeMethod<String>('getAppId') ?? '';
    reportUrlController.text = await settingMethodChannel.invokeMethod<String>('getReportUrl') ?? '';
    showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('标题'),
          content: Container(
            height: 100,
            child: Column(
              children: <Widget>[
                Row(
                  children: <Widget>[
                    const Text('appId: '),
                    Expanded(
                      child: TextField(
                        maxLines: 1,
                        controller: appIdController,
                      ),
                    ),
                  ],
                ),
                Row(
                  children: <Widget>[
                    const Text('reportUrl: '),
                    Expanded(
                      child: TextField(
                        maxLines: 1,
                        controller: reportUrlController,
                      ),
                    ),
                  ],
                )
              ],
            ),
          ),
          actions: <Widget>[
            ElevatedButton(
              child: const Text('确定'),
              onPressed: () {
                final Map<String, dynamic> map = <String, dynamic>{
                  'appId': appIdController.text,
                  'reportUrl': reportUrlController.text
                };
                settingMethodChannel.invokeMethod<void>('update_settings', map);
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }
}
